﻿using System;
using System.Collections;
using NHibernate;
using NHibernate.Cfg;
using System.Collections.Generic;

namespace Business
{
    public class UsersRole
    {
        private ISessionFactory _sessionFactory;
        public UsersRole()
        {
            _sessionFactory = DataObjects.Service.SessionFactory.GetInstance().GetNHibernateFactory();
        }

        public ArrayList GetListByUserId(string UserId)
        {
            ArrayList arrTemp = new ArrayList();
            using (ISession session = _sessionFactory.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                IQuery query = session.CreateSQLQuery("select * from USERS_ROLE where USER_ID =?").AddEntity(typeof(DataObjects.UsersRole));
                query.SetString(0, UserId);
                arrTemp = (ArrayList)query.List();
                tx.Commit();

                return arrTemp;
            }
        }

        //code insert - update - delete 
        public void Insert(DataObjects.UsersRole oUserRole)
        {
            using (ISession session = _sessionFactory.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                session.Save(oUserRole);
                tx.Commit();			        
            }
        }

        public void DeleteByUserId(string UserId)
        {
            ArrayList arrTemp = new ArrayList();
            using (ISession session = _sessionFactory.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                IQuery query = session.CreateSQLQuery("select * from USERS_ROLE where USER_ID =?").AddEntity(typeof(DataObjects.UsersRole));
                query.SetString(0, UserId);
                arrTemp = (ArrayList)query.List();
                
                foreach (DataObjects.UsersRole oUserRole in arrTemp)
                {
                    session.Delete(oUserRole);
                }
                tx.Commit();
            }
        }
    }
}
